const Koa = require('koa');
const fs = require('fs')
const log = require('./mode/index')
const app = new Koa();
// const Router = require('koa-router')
//
// let koarouter = new Router()
// x-response-time
// app.use(async(ctx, next) => {
//   const start = Date.now();
//   await next();
//   const ms = Date.now() - start;
//   console.log(`${ms}`);
//   ctx.set('X-Response-Time', `${ms}ms`);
// });

// // logger

// app.use(async(ctx, next) => {
//   const start = Date.now();
//   await next();
//   const ms = Date.now() - start;
//   console.log(`${ctx.method} ${ctx.url} - ${ms}`);
// });

// // response
app.use(log())

function read(page) {
  return new Promise((resolve, reject) => {
      let viewurl = `./page/${page}`
      fs.readFile(viewurl, "binary", (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      });
    })
    // return new Promise((resolve, reject) => {
    //   let viewUrl = `${page}`
    //   fs.readFile(viewUrl, "binary", (err, data) => {
    //     if (err) {

  //       reject(err)
  //         // console.log(viewUrl)
  //     } else {
  //       resolve(data)
  //     }
  //   })
  // })
}

async function root(url) {
  let view = '404.html'
  switch (url) {
    case '/':
      view = 'index.js'
      break
    case '/cs':
      view = 'cs.html'
      break
    default:
      break
  }
  let html = await read(view)
  return html
}



app.use(async ctx => {
  // app.context.db = db();
  // console.log(ctx.db);ctx.require.url;
  // let ur = ctx.require.url;
  let ur = ctx.request.url
  let html = await root(ur)
    // ctx.body = `Hello World ${ur}`;
  ctx.body = html
    //  const ms = Date.now() - start;
    // console.log(`${ctx} ${ctx.url} - ${ms}`);

});

app.listen(3000);
